package com.euq.mq;

import com.euq.entity.LoginLog;
import com.euq.mapper.LoginLogMapper;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
@RocketMQMessageListener(topic = "login-topic", consumerGroup = "login-consumer-group")
public class LoginConsumer implements RocketMQListener<String> {

    private static final Logger log = LoggerFactory.getLogger(LoginConsumer.class);

    @Autowired
    private LoginLogMapper loginLogMapper;

    @Override
    public void onMessage(String message) {
        log.info("接收到登录消息：{}", message);
        saveLoginLog(message);
    }

    private void saveLoginLog(String logContent) {
        LoginLog log = new LoginLog();
        log.setUsername(logContent.replace("用户登录成功: ", ""));
        log.setLoginTime(LocalDateTime.now());
        log.setDetail(logContent);
        loginLogMapper.insertLoginLog(log);
        LoginConsumer.log.info("登录日志已保存：{}", log);
    }
}